package com.goodmr.passport.log;

import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.sql.Timestamp;

/**
 * 日志数据逻辑
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Service
public class LogDaoImpl implements LogDao {

    private final LogRepository logRepository;

    private final LogDetailRepository logDetailRepository;

    @Autowired
    public LogDaoImpl(LogRepository logRepository,
                      LogDetailRepository logDetailRepository) {
        this.logRepository = logRepository;
        this.logDetailRepository = logDetailRepository;
    }

    /**
     * 生成帐号日志
     *
     * @param model log model
     * @return log model
     */
    @Override
    @Transactional
    public LogModel generate(@NonNull LogModel model) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        model.setCreatedAt(timestamp);

        LogEntity logEntity = new LogEntity();

        BeanUtils.copyProperties(model, logEntity);

        logEntity.setType(model.getLogType().getValue());

        logEntity = logRepository.save(logEntity);

        model.setLogId(logEntity.getId());

        generateDetail(model);

        return model;
    }

    /**
     * 生成日志内容
     *
     * @param model log model
     */
    private void generateDetail(@NonNull LogModel model) {

        if (StringUtils.hasText(model.getContent())) {
            LogDetailEntity logDetailEntity = new LogDetailEntity();
            logDetailEntity.setLogId(model.getLogId());
            logDetailEntity.setContent(model.getContent());

            logDetailRepository.save(logDetailEntity);
        }
    }
}
